import Vue from 'vue'
import VueRouter from 'vue-router'

import Home from '../views/Home.vue'
import News from '../views/News.vue'
import Zixun from '../views/Zixun.vue'
// import Mine from '../views/Mine.vue'
// import Login from '../views/Login.vue'

import Nav from '../components/home/Nav'
import Detail from '../components/home/Detail'

Vue.use(VueRouter)

const routes = [
  {
    path: '*', // 通配符
    redirect: '/home'
  },
  {
    path: '/home',
    component: Home,
    children: [
      {
        path: '/nav',
        component: Nav
      },
      // {
      //   path: '',
      //   redirect: '/nav'  //重定向到home/nav
      // },
    ]
  },
  // {
  //   path: '/detail/:myid',//动态路由:myid可以随意匹配
  //   component: Detail,
  //   name: 'myDetail',//路由名字
  // },
  {
    path: '/detail',
    component: Detail,
  },
  {
    path: '/news',
    component: News
  }, {
    path: '/zixun',
    component: Zixun
  },
  {
    path: '/mine',
    // component: Mine
    component: import(/* webpackChunkName: "group-foo" */ '../views/Mine.vue')//Mine.vue和Login.vue打包时合并在一起,js名为group-foo.js
  }, {
    path: '/login',
    // component: Login
    // component: () => import('../views/Login.vue'),// 路由懒加载
    component: import(/* webpackChunkName: "group-foo" */ '../views/Login.vue')
  }
]

const router = new VueRouter({
  mode: 'history', // 去除地址栏中# hash,history
  base: process.env.BASE_URL,
  routes
})
//使用场景：例如在用户未登录时
// 使用 router.beforeEach 注册一个全局前置守卫
// to: Route: 即将要进入的目标 路由对象
// from: Route: 当前导航正要离开的路由
// next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
router.beforeEach((to, form, next) => {
  // next()// 任何路由过来都放行
  // console.log(to)
  let auth = ['/center', '/mine', '/cart', '/money']
  if (auth.includes(to.fullPath)) {//只要在auth里面的
    console.log('验证token');
    //检查是否有token，如果没有，重定向到login
    if (!localStorage.getItem("token")) {
      next("/login");
    } else {
      next()
    }
  } else {
    next();
  }
})

export default router
